from plugin import plugin
from threading import Timer
import re

__doc__ = "remind"

class remind(plugin):
	"Reminds you of things"
	
	def __init__(self):
		self._version = '3.0 development'
		self.regex = re.compile('(?:me in )?(\d+) ([a-z]+) (.*)')
		self.reminders = []

	def __del__(self):
		for t in self.reminders:
			t.cancel()
		self.reminders = None

	def remind(self, msg, args):
		"Start a timer! Usage: .remind (me in) [number] [seconds, minutes, hours, days] [message] (e.g. .remind me in 5 hours to cook dinner)"
		m = self.regex.match(args)
		if m:
			g = m.groups()
			time = float(g[0])
			time_period = g[1]
			if time_period == 'minutes' or time_period == 'minute':
				time = time * 60
			if time_period == 'hours' or time_period == 'hour':
				time = time * 60 * 60
			if time_period == 'days' or time_period == 'day':
				time = time * 60 * 60 * 24
			reminder = g[2]
			self._irc.reply(msg, 'I will remind you about that in ' + g[0] + ' ' + time_period)
			try:
				t = Timer(time, self._onTimeup, [msg, reminder])
				self.reminders.append(t)
				t.start()
			except:
				self._irc.reply(msg, 'Error creating timer')
				pass
		else:
			self._irc.reply(msg, self.remind.__doc__)

	def _onTimeup(self, msg, reminder):
		self._irc.reply(msg, 'you asked me to remind you to: ' + reminder)
